package profitshare

import (
	"crypto/tls"
	"wxsdk/wxpay/core"

	"wxsdk/wxpay/utils/mapstruct"
	//"github.com/astaxie/beego"
)

//type Receiver struct {
//	Type         string   `json:"type"`         //
//	Account      string   `json:"account"`      //
//	Amount       int      `json:"amount"`       //
//	Description  string   `json:"description"`  //
//}
//
//type ProfitSharingReq struct {
//	Appid          string   `xml:"appid"`                     //微信分配的小程序ID
//	MchId          string   `xml:"mch_id"`                    //微信支付分配的商户号
//	SubAppid       string   `xml:"sub_appid,omitempty"`       //小程序的APPID,当前调起支付的小程序APPID(服务商特有参数)
//	SubMchId       string   `xml:"sub_mch_id,omitempty"`      //微信支付分配的子商户号(服务商特有参数)
//	NonceStr       string   `xml:"nonce_str"`                 //随机字符串
//	Sign           string   `xml:"sign"`                      //签名
//	SignType       string   `xml:"sign_type,omitempty"`       //签名类型
//	TransactionId  string   `xml:"transaction_id,omitempty"`  //微信订单号
//	OutOrderNo     string   `xml:"out_order_no,omitempty"`    //商户分账单号
//	Receivers      string   `xml:"receivers"`                 //分账接收方列表
//}
//
//type ProfitSharingRsp struct {
//	BaseResponse `xml:",innerXml,omitempty"`
//	TransactionId string `xml:"transaction_id,omitempty"`  // 微信订单号
//	OutOrderNo    string `xml:"out_order_no,omitempty"`    // 商户分账单号
//	OrderId       string `xml:"order_id,omitempty"`        // 微信分账单号
//}
//
//
func  _ProfitSharing(appId,mchId,subAppid,subMchId,appSecret,transactionId,orderIdStr,receivers,crt,key string) (*ProfitSharingRsp,error){
	var (
	    req = new(ProfitSharingReq)
	    rsp = new(ProfitSharingRsp)
		ReqUrl string = "https://api.mch.weixin.qq.com/secapi/pay/multiprofitsharing"
	)
	cert, err := tls.X509KeyPair([]byte(crt), []byte(key))
	if err != nil {
		return rsp, err
	}
	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
	}
	client := core.GetWxPayClient(appId,mchId,appSecret,tlsConfig)
	req.Appid = appId
	req.MchId = mchId
	if len(subAppid) > 0 {
	   req.SubAppid = subAppid
	}
	if len(subMchId) > 0 {
	   req.SubMchId = subMchId
	}
	req.TransactionId = transactionId
	req.OutOrderNo =  orderIdStr      //商户订单号
	req.Receivers = receivers        //商户退款单号
	rspMap, err := client.ExcuteMap(ReqUrl, req)
    if err != nil {
		return rsp, err
	}
	err = mapstruct.Map2Struct(rspMap, rsp, "xml")
	if err != nil {
		return rsp, err
	}
	return rsp, nil
}

